package authorization;

import com.sun.xacml.EvaluationCtx;

import com.sun.xacml.attr.StringAttribute;

import com.sun.xacml.ctx.Attribute;
import com.sun.xacml.ctx.RequestCtx;
import com.sun.xacml.ctx.Subject;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.HashSet;
import java.util.Set;

/**
 * Just another utility class: make a request complaint to XACML standards
 * 
 * @author pasquale
 *
 */
public class RequestBuilder{
	static final String ACTION_IDENTIFIER = "urn:oasis:names:tc:xacml:1.0:action:action-id";
	static final String RESOURCE_IDENTIFIER = "urn:oasis:names:tc:xacml:1.0:resource:resource-id";
	static final String SUBJECT_IDENTIFIER = "urn:oasis:names:tc:xacml:1.0:subject:subject-id";
	static final String SUBJECT_ROLE_IDENTIFIER = "urn:oasis:names:tc:xacml:2.0:subject:role";            

	public static Set<Subject> setupSubjects(String role) throws URISyntaxException {
		Set<Attribute> attributes = new HashSet<Attribute>();
		Set<Subject> subjects = new HashSet<Subject>();

		String ruolo = role;

		if(ruolo==null){
			subjects=null;
		}else{
			attributes.add(new Attribute(new URI(SUBJECT_ROLE_IDENTIFIER),
					null, null,
					new StringAttribute(ruolo)));

			subjects.add(new Subject(attributes));
		}

		return subjects;
	}

	/**
	 * Creates a Resource specifying the resource-id, a required attribute.
	 *
	 * @return a Set of Attributes for inclusion in a Request
	 *
	 * @throws URISyntaxException if there is a problem with a URI
	 */
	public static Set<Attribute> setupResource(String resource1) throws URISyntaxException {
		Set<Attribute> resource = new HashSet<Attribute>();

		// the resource being requested : è una URI ma passata come stringa
		StringAttribute value =
			new StringAttribute(resource1);

		// create the resource using a standard, required identifier for
		// the resource being requested
		resource.add(new Attribute(new URI(EvaluationCtx.RESOURCE_ID),
				null, null, value));

		return resource;
	}

	/**
	 * Creates an Action specifying the action-id, an optional attribute.
	 *
	 * @return a Set of Attributes for inclusion in a Request
	 *
	 * @throws URISyntaxException if there is a problem with a URI
	 */
	public static Set<Attribute> setupAction(String action1) throws URISyntaxException {
		Set<Attribute> action = new HashSet<Attribute>();

		// this is a standard URI that can optionally be used to specify
		// the action being requested
		URI actionId =
			new URI(ACTION_IDENTIFIER);

		// create the action
		action.add(new Attribute(actionId, null, null,
				new StringAttribute(action1)));

		return action;
	}


	public static RequestCtx createXACMLRequest(String resource,String role,String action) throws Exception{

		RequestCtx XACMLrequest = new RequestCtx(setupSubjects(role), 
				setupResource(resource),setupAction(action), 
				new HashSet());
		return XACMLrequest;
	}

}

